package com.itheima.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class UserServiceTest {
    private SqlSession sqlSession;

    @Before
    public void init() throws IOException {
        // 加载核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");

        // 获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 获取SqlSessionFactory
        SqlSessionFactory factory = builder.build(in);

        // 获取连接SqlSession
        sqlSession = factory.openSession();
    }

    @After
    public void close() {
        // 提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

    // 分页查询
    @Test
    public void findByPages(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        // 查询之前, 设置分页参数
        // pageNum：当前页数，pageSize：每页显示条数
        PageHelper.startPage(1,3);

        // 查询
        List<User> users = mapper.findAll();
        for (User user : users) {
            System.out.println(user);
        }

        //其他分页的数据
        PageInfo<User> info = new PageInfo<User>(users);
        System.out.println("总条数：" + info.getTotal());
        System.out.println("总页数：" + info.getPages());
        System.out.println("当前页：" + info.getPageNum());
        System.out.println("每页显示条数：" + info.getPageSize());
        System.out.println("上一页：" + info.getPrePage());
        System.out.println("下一页：" + info.getNextPage());
        System.out.println("是否是第一页：" + info.isIsFirstPage());
        System.out.println("是否是最后一页：" + info.isIsLastPage());

    }
}
